package middleware

import (
	"gin-init/internal/types"
	"gin-init/pkg/logger"
	"net/http"
	"runtime/debug"

	"github.com/gin-gonic/gin"
)

func Recovery() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				logger.Errorw("Recover", "error", err, "stack", string(debug.Stack()))
				resp := types.ErrorRespone{
					ErrCode: http.StatusInternalServerError,
					ErrMsg:  http.StatusText(http.StatusInternalServerError),
					ErrTips: "系统错误",
				}
				ctx.AbortWithStatusJSON(http.StatusInternalServerError, resp)
			}
		}()
		ctx.Next()
	}
}
